<template>
    <div class="wh-100  d-flex fs-14" v-loading="loading">
        <!--左边-->
        <div class="h-100 flex-1 w-0  py-12 px-12" style="background-color: #ffffff">
            <!--头部-->
            <div class="d-flex-between-center" style="height: 60px">
                <div>
                    <!--                    <Button type="primary" @click="handleAdd">添加账号</Button>-->
                    <!--                    <Button @click="handleDel(2)">批量删除</Button>-->
                    <Button @click="handleResetPassword">重置用户密码</Button>
                    <Button @click="handleExportSelection">导出所选数据</Button>
                    <Button @click="handleExportAll">导出全部数据</Button>
                </div>
                <check-password ref="checkPass" @on-success="resetPass" />
                <div>
                    <Button style="width: 40px" :icon="showRight ? `ios-arrow-forward` : `ios-arrow-back`" @click.native="showRight = !showRight" type="primary"></Button>
                </div>
            </div>
            <!--表格-->
            <div class=" bor-base-b" v-ref-height="refHeight" style="height: calc(100% - 120px)">
                <!--数据-->
                <Table class="mt-12" :columns="tableColumns" :height="refHeight.value" :data="tableData" @on-selection-change="selectChange">
                    <template slot="status" slot-scope="{ row, index }">
                        <Badge status="error" v-if="row.status == '-1'" text="禁用" />
                        <Badge status="success" v-else text="启用" />
                    </template>
                    <template slot-scope="{ row, index }" slot="action">
                        <div class="wh-100 d-flex-around-center">
                            <!--                            <div class="table-btn mr-12" @click="editData(row)">编辑</div>-->
                            <div class="table-btn mr-12" @click="forbidden(row)" v-if="row.status == '0'">禁用</div>
                            <div class="table-btn mr-12" @click="forbidden(row)" v-if="row.status == '-1'">启用</div>
                            <!--                            <div class="table-btn"  @click="deleteData(row)">删除</div>-->
                        </div>
                    </template>
                </Table>
            </div>
            <!--分页-->
            <div class=" d-flex-center" style="height: 60px">
                <Page
                    :current="searchForm.pageNumber"
                    :total="total"
                    :page-size="searchForm.pageSize"
                    @on-change="changePage"
                    @on-page-size-change="changePageSize"
                    :page-size-opts="[10, 20, 50, 100, 200]"
                    size="small"
                    show-total
                    show-elevator
                    show-sizer
                ></Page>
            </div>
        </div>
        <!--右边-->
        <div class="h-100  ml-12 px-12" :class="!showRight ? 'hidden-table' : 'edit-table'" style="width: 400px;background-color: #ffffff">
            <div class="bor-base-b" style="height: calc(100% - 60px)">
                <div class="fw-6 d-flex" style="height:60px;align-items: center;">
                    {{ rightTitle }}
                </div>
                <div v-if="showRightType === '1'" class="ml-24 mr-12">
                    <Form ref="formRef" :model="formValidateSelect" :rules="ruleValidate" :label-width="80">
                        <FormItem label="姓名" prop="name" key="2">
                            <Input v-model="formValidateSelect.name" placeholder=""></Input>
                        </FormItem>
                        <FormItem label="手机号" prop="epRegPhone" key="5">
                            <Input v-model="formValidateSelect.epRegPhone" placeholder=""></Input>
                        </FormItem>
                        <FormItem label="单位名称" prop="enterpriseName" key="6">
                            <Input v-model="formValidateSelect.enterpriseName" placeholder=""></Input>
                        </FormItem>
                        <FormItem label="所属部门" prop="departmentName" key="7">
                            <Input v-model="formValidateSelect.departmentName" placeholder=""></Input>
                        </FormItem>
                        <FormItem label="担任的职位" prop="office" key="8">
                            <Input v-model="formValidateSelect.office" placeholder=""></Input>
                        </FormItem>
                        <FormItem label="工作邮箱" prop="email" key="9">
                            <Input v-model="formValidateSelect.email" placeholder=""></Input>
                        </FormItem>
                        <FormItem label="工作电话" prop="workPhone" key="10">
                            <Input v-model="formValidateSelect.workPhone" placeholder=""></Input>
                        </FormItem>
                        <FormItem label="传真" prop="fax" key="11">
                            <Input v-model="formValidateSelect.fax" placeholder=""></Input>
                        </FormItem>
                    </Form>
                </div>
                <div v-if="showRightType === '3'" class="ml-24 mr-12">
                    <Form ref="formRef" :model="formValidate" :rules="ruleValidate" :label-width="80">
                        <FormItem label="账号" prop="account" key="2" :rules="[{ required: true, message: '账号不能为空', trigger: 'blur' }]">
                            <Input v-model="formValidate.account" placeholder=""></Input>
                        </FormItem>
                        <FormItem label="密码" prop="password" v-if="showType === 1" key="3" :rules="[{ required: true, message: '密码不能为空', trigger: 'blur' }]">
                            <Input v-model="formValidate.password" placeholder=""></Input>
                        </FormItem>
                        <FormItem label="负责人姓名" prop="personName" key="5">
                            <Input v-model="formValidate.personName" placeholder=""></Input>
                            <!--              <Select v-model="formValidate.submarketCode" placeholder="选择市场名称" clearable filterable>-->
                            <!--                <Option v-for="item in marketNameList" :value="item.value" :key="item.value">{{ item.title }}</Option>-->
                            <!--              </Select>-->
                        </FormItem>
                        <FormItem label="手机号" prop="mobile" key="6">
                            <Input v-model="formValidate.mobile" placeholder=""></Input>
                        </FormItem>
                        <FormItem label="所属部门" prop="workName" key="7">
                            <Input v-model="formValidate.workName" placeholder=""></Input>
                        </FormItem>
                        <FormItem label="担任的职位" prop="workPosition" key="8">
                            <Input v-model="formValidate.workPosition" placeholder=""></Input>
                        </FormItem>
                        <FormItem label="工作邮箱" prop="workEmail" key="9">
                            <Input v-model="formValidate.workEmail" placeholder=""></Input>
                        </FormItem>
                        <FormItem label="工作电话" prop="workPhone" key="10">
                            <Input v-model="formValidate.workPhone" placeholder=""></Input>
                        </FormItem>
                        <FormItem label="传真" prop="fix" key="11">
                            <Input v-model="formValidate.fix" placeholder=""></Input>
                        </FormItem>
                    </Form>
                </div>
            </div>
            <div class="d-flex flex-row-reverse" style="height: 60px;align-items: center;">
                <Button v-if="showRightType === '1'" class="float-right" type="primary" @click="selectData">提交</Button>
                <Button v-if="showRightType === '3'" class="float-right" type="primary" @click="handleSubmit">提交</Button>
                <Button v-if="showRightType === '1'" class="float-right" @click="handleCancel">取消</Button>
                <Button v-if="showRightType === '1'" class="float-right" @click="reset">重置</Button>
            </div>
        </div>
    </div>
</template>
<script>
import checkPassword from '@/views/my-components/xboot/check-password.vue';
import { exportUnitPersonInfoByIdsAPI, getUnitAccountDataPageAPI, resetPwdAPI } from '@/api/bys/unitAccountNumber/unitAccountNumberApis';
import { delAllByIdsAPI } from '@/api/bys/unitAccountNumber/unitAccountNumberApis';
import { disableUnitAccountAPI } from '@/api/bys/unitAccountNumber/unitAccountNumberApis';
import { updateAccountDataAPI } from '@/api/bys/unitAccountNumber/unitAccountNumberApis';
import { addUnitAccountDataAPI } from '@/api/bys/unitAccountNumber/unitAccountNumberApis';
import { exportUnitPersonInfoAPI } from '@/api/bys/unitAccountNumber/unitAccountNumberApis';

export default {
    components: { checkPassword },
    data() {
        return {
            loading: false,
            showRight: false,
            showType: 1,
            showRightType: '1', //1查询2编辑3添加
            rightTitle: '查询区',
            total: 0,
            refHeight: { value:0 },
            searchForm: {
                pageNumber: 1,
                pageSize: 10
            },
            tableColumns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '序号',
                    type: 'index',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '手机号（账号）',
                    key: 'username',
                    align: 'center'
                },
                {
                    title: '姓名',
                    key: 'name',
                    align: 'center'
                },
                {
                    title: '单位名称',
                    key: 'enterpriseName',
                    align: 'center'
                },
                {
                    title: '工作电话',
                    key: 'workPhone',
                    align: 'center'
                },
                {
                    title: '工作邮箱',
                    key: 'email',
                    align: 'center'
                },
                {
                    title: '状态',
                    slot: 'status',
                    align: 'center'
                },
                {
                    title: '操作',
                    slot: 'action',
                    align: 'center',
                    width: 180,
                    fixed: 'right'
                }
            ],
            tableData: [],
            formValidate: {
                account: '',
                fix: '',
                mobile: '',
                password: '',
                personName: '',
                submarketName: '',
                submarketCode: '',
                userRoleId: '',
                workEmail: '',
                workName: '',
                workPhone: '',
                workPosition: ''
            },
            formValidateSelect: {
                name: '',
                password: '',
                epRegPhone: '',
                enterpriseName: '',
                departmentName: '',
                office: '',
                email: '',
                fax: ''
            },
            ruleValidate: {
                // submarketCode: [
                //   { required: true, message: '请选择市场', trigger: 'change' }
                // ],
                // account: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
                // password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
            },
            ids: '',
            //table选中列表
            selectDataList: []
        };
    },
    mounted() {
        this.postData();
    },
    methods: {
        postData() {
            this.loading = true;
            console.log(this.formValidateSelect);
            getUnitAccountDataPageAPI(this.searchForm, this.formValidateSelect).then(res => {
                console.log(res, '企业号信息');
                if (res.success) {
                    this.tableData = res?.result?.records || [];
                    this.total = res?.result?.total || 0;
                    this.loading = false;
                } else {
                    this.loading = false;
                }
            });
        },
        selectData() {
            this.loading = true;
            getUnitAccountDataPageAPI({ ...this.searchForm, ...this.formValidateSelect }).then(res => {
                console.log(res, '企业号信息');
                if (res.success) {
                    this.tableData = res?.result?.records || [];
                    this.total = res?.result?.total || 0;
                    this.loading = false;
                } else {
                    this.loading = false;
                }
            });
        },
        changeBackTask(v) {
            this.formValidate.account = v;
        },
        selectChange(selectdata) {
            console.log(selectdata, 'selectChange');
            this.selectDataList = selectdata;
        },
        //添加账号
        handleAdd() {
            this.$nextTick(() => {
                this.showRight = true;
                this.rightTitle = '添加区';
                this.showType = 1;
                this.showRightType = '3';
                this.formValidate = {
                    account: '',
                    fix: '',
                    mobile: '',
                    password: '',
                    personName: '',
                    submarketName: '',
                    submarketCode: '',
                    workEmail: '',
                    workName: '',
                    workPhone: '',
                    workPosition: ''
                };
            });
        },
        //批量删除
        handleDel(type) {
            if (type == 1) {
                this.$Modal.confirm({
                    title: '确认删除',
                    content: '您确认要删除该企业用户?',
                    // loading: true,
                    onOk: () => {
                        delAllByIdsAPI({ ids: this.ids }).then(res => {
                            if (res.success) {
                                this.$message.success(res.message);
                                this.postData();
                            }
                        });
                    }
                });
            }
            if (type == 2) {
                console.log(this.selectDataList, 'this.selectDataList');
                if (this.selectDataList.length == 0) {
                    this.$message.warning('您还未选择要删除的数据');
                } else {
                    this.$Modal.confirm({
                        title: '确认删除',
                        content: '您确认要删除所选的 ' + this.selectDataList.length + ' 条数据?',
                        // loading: true,
                        onOk: () => {
                            this.ids = this.selectDataList
                                .map(obj => {
                                    return obj.id;
                                })
                                .join(',');
                            delAllByIdsAPI({ ids: this.ids }).then(res => {
                                if (res.success) {
                                    this.$message.success(res.message);
                                    this.postData();
                                }
                            });
                        }
                    });
                }
            }
        },
        //重置用户密码
        handleResetPassword() {
            if (this.selectDataList.length <= 0) {
                this.$Message.warning('您还未选择要重置密码的用户');
                return;
            }
            this.$refs.checkPass.show();
        },
        resetPass(e, i) {
            this.$Modal.confirm({
                title: '确认重置',
                content: '您确认要重置所选的 ' + this.selectDataList.length + ' 条用户数据密码为' + i + '吗？',
                loading: true,
                onOk: () => {
                    let ids = '';
                    this.selectDataList.forEach(function(e) {
                        ids += e.id + ',';
                    });
                    ids = ids.substring(0, ids.length - 1);
                    resetPwdAPI({ ids: ids, password: i }).then(res => {
                        this.$Modal.remove();
                        if (res.success) {
                            this.$Message.success('操作成功');
                            this.postData();
                        }
                    });
                }
            });
        },
        //导入数据
        handleImport() {},
        //导出所选数据
        handleExportSelection() {
            if (this.selectDataList.length <= 0) {
                this.$message.warning('您还未选择要导出的数据');
            } else {
                this.ids = this.selectDataList
                    .map(obj => {
                        return obj.id;
                    })
                    .join(',');
                exportUnitPersonInfoByIdsAPI({ ids: this.ids }).then(res => {
                    // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
                    const blob = new Blob([res], { type: 'charset=utf-8' });
                    let url = window.URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.style.display = 'none';
                    link.href = url;
                    link.setAttribute('download', '市场账号信息.xlsx');
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link); // 删除节点
                    window.URL.revokeObjectURL(url); //释放该 url
                });
            }
        },
        //导出全部数据
        handleExportAll() {
            exportUnitPersonInfoAPI().then(res => {
                // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
                const blob = new Blob([res], { type: 'charset=utf-8' });
                let url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.style.display = 'none';
                link.href = url;
                link.setAttribute('download', '市场账号信息.xlsx');
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link); // 删除节点
                window.URL.revokeObjectURL(url); //释放该 url
            });
        },
        //删除
        deleteData(data) {
            this.ids = data.id;
            this.handleDel(1);
        },
        //编辑
        editData(data) {
            this.$nextTick(() => {
                this.showRight = true;
                (this.rightTitle = '编辑区'), (this.showType = 2);
                this.formValidate = data;
            });
        },
        //禁用启用
        forbidden(data) {
            disableUnitAccountAPI({ id: data.id }).then(res => {
                if (res.success) {
                    this.$message.success(res.message);
                    this.postData();
                }
            });
        },
        //提交
        handleSubmit() {
            this.$refs.formRef.validate(valid => {
                if (valid) {
                    if (this.formValidate.submarketCode) {
                        let a = this.marketList.filter(e => e.submarketCode == this.formValidate.submarketCode);
                        this.formValidate.submarketName = a[0].submarketName;
                    }
                    if (this.showType == 1) {
                        addUnitAccountDataAPI(this.formValidate).then(res => {
                            if (res.success) {
                                this.showRight = false;
                                this.$message.success('添加成功！');
                                console.log(1111);
                                this.postData();
                            }
                        });
                    }
                    if (this.showType == 2) {
                        updateAccountDataAPI(this.formValidate).then(res => {
                            if (res.success) {
                                this.showRight = false;
                                this.$message.success('修改成功！');
                                this.postData();
                            }
                        });
                    }
                } else {
                    console.log('填写');
                }
            });
        },
        //取消
        handleCancel() {
            this.formValidateSelect = {};
            this.showRight = false;
        },
        reset() {
            this.formValidateSelect = {};
        },
        //分页
        changePage(v) {
            this.searchForm.pageNumber = v;
            this.postData();
            this.clearSelectAll();
        },
        changePageSize(v) {
            this.searchForm.pageSize = v;
            this.postData();
        }
    }
};
</script>
<style scoped>
.table-btn {
    color: #1677ff;
    cursor: pointer;
}

.edit-table {
    width: 330px;
    background-color: #fff;
}

.hidden-table {
    width: 0;
    display: none;
}
</style>